
var hmConfig = require('../hmConfig.js');
var crypto = require('crypto');
var request = require('request');

var PARSE_HOST = 'http://127.0.0.1:1337/parse';

var PARSE_HEADERS = {
    'Content-Type': 'application/json;charset=utf-8',
    'X-Parse-Application-Id':'myAppId',
    'X-Parse-Master-Key':'masterKey'
};

var JADE_VAR = {
    __PLUGINS_ROOT__: '/public/plugins',
    __BOWER_ROOT__: '/bower_components',
    __CSS_ROOT__: '/public/stylesheets',
    __JS_ROOT__: '/public/javascripts',
    __IMAGES_ROOT__: '/public/images',
    __COMPRESSED_SUFFIX__:""
};

var apiRequest = function () {
    function runRequest(){
        return p = new Promise(
            function (resolve,reject) {
                function getBoday(){
                    resturn = [];
                    for(var i=0;i<4;i++){
                        console.log(31312);
                        resturn[i] = new Promise(
                            function(resolve,reject){
                                request('http://www.baidu.com', function (err,response,body) {
                                    resolve(body);
                                })
                            }
                        )
                    }
                    console.log(resturn);
                    return resturn;
                }

                Promise.all(getBoday()).then(function (results) {
                    console.log(results.length);
                    resolve(results);
                })
            }
        );
    }
    runRequest().then(function (body) {
        return body;
    });
};

var validateRequest = function( params,callback ){
    if(!params.sign){
        callback(0,"非法访问");
        return;
    }
    if(!params.timeStr){
        callback(0,"非法访问");
        return;
    }

    //过期检测
    var requestTimeStamp = new Date().getTime();
    if(requestTimeStamp - params.timeStr > 5*60*1000){
        callback(0,"请求过期");
        return;
    }
    var signStr = params.sign;
    //然后将除sign以外的参数升序排列后拼接
    var keys = Object.keys(params).sort();
    var waitSign = '';
    keys.forEach(function(i){
        if(params[i] && i != 'sign'){
            waitSign += _utf_encode(String(params[i]));
        }
    });
    //检查生成参数列
    if(!waitSign){
        callback(-2,"核验字段错误");
        return;
    }
    //生成本地签名
    var localSign = crypto.createHash('md5').update(waitSign).digest('hex');
    if(localSign != signStr){
        callback(3,"签名不通过");
    }else{
        callback(1,"请求成功");
    }
};


var createdSign = function (params) {

    var keys = Object.keys(params).sort();
    var waitSign = '';
    keys.forEach(function(i){
        if(req.query[i] && i != 'sign'){
            waitSign += _utf_encode(String(req.query[i]));
        }
    });

    if(!waitSign){
        callback(-2,"核验字段错误");
        return;
    }

    return crypto.createHash('md5').update(waitSign).digest('hex');
};

/**
 * utf编码字符串
 * @param string
 * @returns {string}
 * @private
 */
function _utf_encode(string){
    string = string.replace(/rn/g,"n");
    var utftext ="";
    for (var n = 0; n < string.length; n++){
        var c = string.charCodeAt(n);
        if (c < 128){
            utftext += String.fromCharCode(c);
        }
        else if((c > 127) && (c < 2048)){
            utftext += String.fromCharCode((c >> 6) | 192);
            utftext += String.fromCharCode((c & 63) | 128);
        }
        else{
            utftext += String.fromCharCode((c >> 12) | 224);
            utftext += String.fromCharCode(((c >> 6) & 63) | 128);
            utftext += String.fromCharCode((c & 63) | 128);
        }
    }
    return utftext;
}


var apiParseRequest = function(method,path,params){
    var options = {
        url: PARSE_HOST + path,
        method:method,
        form:params,
        headers: PARSE_HEADERS
    };
    return new Promise(
        function(resolve,reject){
            request(options,function(error,response,body){
                var responseJSON = JSON.parse(body);
                resolve(responseJSON);
            });
        }
    )
};

module.exports = {
    JADE_VAR:JADE_VAR,
    _utf_encode:_utf_encode,
    validateRequest:validateRequest,
    createdSign:createdSign,
    apiParseRequest:apiParseRequest
};